package com.aiyige.utils;

import android.text.TextUtils;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.model.Subject;
import com.aiyige.model.moment.backup.StatisticsBackup;

import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by xiachao on 2017/10/26.
 */

public class StringUtils {


    /**
     * Compares two version strings.
     * <p>
     * Use this instead of String.compareTo() for a non-lexicographical
     * comparison that works for version strings. e.g. "1.10".compareTo("1.6").
     *
     * @param str1 a string of ordinal numbers separated by decimal points.
     * @param str2 a string of ordinal numbers separated by decimal points.
     * @return The result is a negative integer if str1 is _numerically_ less than str2.
     * The result is a positive integer if str1 is _numerically_ greater than str2.
     * The result is zero if the strings are _numerically_ equal.
     * @note It does not work if "1.10" is supposed to be equal to "1.10.0".
     */
    public static int versionCompare(String str1, String str2) {
        String[] vals1 = str1.split("\\.");
        String[] vals2 = str2.split("\\.");
        int i = 0;
        // set index to first non-equal ordinal or length of shortest version string
        while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
            i++;
        }
        // compare first non-equal ordinal number
        if (i < vals1.length && i < vals2.length) {
            int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
            return Integer.signum(diff);
        }
        // the strings are equal or one string is a substring of the other
        // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
        return Integer.signum(vals1.length - vals2.length);
    }

    /**
     * 用于格式化评论点数、点赞数、收藏数、浏览数等 <br/>
     * 1~9999：显示实际数字
     * 1W~99.9W：X.X万（四舍五入，保留一位小数）
     * 大于100W：X万（四舍五入，取整）
     *
     * @param num
     * @return
     * @author wzj
     */
    public static String formatNum(Integer num) {
        StringBuffer sb = new StringBuffer();
        if (null != num && num >= 0) {
            if (0 <= num && num <= 9999) {
                sb.append(num);
                return sb.toString();
            } else if (10000 <= num && num <= 999999) {
                double temp = num / 10000.0;
                DecimalFormat df = new DecimalFormat("######0.0");
                sb.append(df.format(temp)).append("万");
            } else if (num >= 1000000) {
                sb.append(num / 10000).append("万");
            }
        } else {
            sb.append(0);
        }

        return sb.toString();
    }

    public static String escapeEmptyString(String str) {
        return escapeEmptyStringWithDefault(str, "");
    }

    public static String escapeEmptyStringWithDefault(String str, String def) {
        return TextUtils.isEmpty(str) ? def : str;
    }

    public static String formatNum(Long num) {
        StringBuffer sb = new StringBuffer();
        if (null != num && num >= 0) {
            if (0 <= num && num <= 9999) {
                sb.append(num);
                return sb.toString();
            } else if (10000 <= num && num <= 999999) {
                double temp = num / 10000.0;
                DecimalFormat df = new DecimalFormat("######0.0");
                sb.append(df.format(temp)).append("万");
            } else if (num >= 1000000) {
                sb.append(num / 10000).append("万");
            }
        } else {
            sb.append(0);
        }

        return sb.toString();
    }


    /**
     * 爱一格价格保留2位小数
     *
     * @param price
     * @return
     */
    public static String priceFormat(double price) {
        return String.format("%.2f", price);
    }

    public static String priceFormatEscapeRedundantTailZero(double price) {
        String s = String.format("%.2f", price);
        s = !s.contains(".") ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");
        return s;
    }

    public static String platformDividendFormat(double dividend) {
        String s = String.valueOf(dividend);
        s = !s.contains(".") ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");
        return s;
    }

    /**
     * 将媒体的秒级的时长格式化为xx'xx''的形式
     *
     * @param duration 媒体的秒级的时长
     * @return 格式化好的字符串
     */
    public static String formatMediaDuration(long duration) {
        long minute = duration / 60;
        long second = duration % 60;
        return minute + "\'" + second + "\"";
    }

    /**
     * 将媒体的毫秒级的时长格式化为xx:xx的形式
     *
     * @param duration 媒体的秒级的时长
     * @return 格式化好的字符串
     */
    public static String formatMediaDurationMS(long duration) {
        duration = duration / 1000;
        long minute = duration / 60;
        long second = duration % 60;
        String minuteString = minute < 10 ? ("0" + minute) : String.valueOf(minute);
        String secondString = second < 10 ? ("0" + second) : String.valueOf(second);
        return minuteString + ":" + secondString;
    }

    /**
     * 将媒体的毫秒级的时长格式化为xx'xx''的形式
     *
     * @param duration 媒体的秒级的时长
     * @return 格式化好的字符串
     */
    public static String formatMediaDurationMS2(long duration) {
        duration = duration / 1000;
        long minute = duration / 60;
        long second = duration % 60;
        String minuteString = minute < 10 ? ("0" + minute) : String.valueOf(minute);
        String secondString = second < 10 ? ("0" + second) : String.valueOf(second);
        return minuteString + "\'" + secondString + "\"";
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }


    public static String getTextString(String string) {
        return TextUtils.isEmpty(string) ? "" : string;
    }

    public static String getString(int resId) {
        return MyApp.getAppContext().getString(resId);
    }

    public static String getString(int resId, Object... formatArgs) {
        return MyApp.getAppContext().getString(resId, formatArgs);
    }


    public static String getBuyInfoText(String subject, StatisticsBackup statisticsBackup) {
        if (TextUtils.isEmpty(subject)) {
            return MyApp.getAppContext().getResources().getString(R.string.watch_count_value, (statisticsBackup != null ? statisticsBackup.getViewCount() : 0) + "");
        }
        if (subject.equals(Subject.video_course) || subject.equals(Subject.major_course) || subject.equals(Subject.training_course)
                || subject.equals(Subject.training_card)) {
            return MyApp.getAppContext().getString(R.string.sell_count_value, (statisticsBackup != null ? statisticsBackup.getSellCount() : 0) + "");
        } else {
            return MyApp.getAppContext().getString(R.string.watch_count_value, (statisticsBackup != null ? statisticsBackup.getViewCount() : 0) + "");
        }
    }

    public static boolean safeEquals(String a, String b) {
        if (TextUtils.isEmpty(a) && TextUtils.isEmpty(b)) {
            return true;
        } else if (TextUtils.isEmpty(a) || TextUtils.isEmpty(b)) {
            return false;
        } else {
            return a.equals(b);
        }
    }

}
